package com.rcadmin.busi.file.action;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.rcadmin.busi.file.dto.FileInfo;
import com.rcadmin.common.prop.FileResProp;
import com.rcadmin.core.app.action.ResponseData;
import com.rcadmin.core.app.action.ResponseUtils;
import com.rcadmin.core.web.BaseAction;

@RestController
public class FileController extends BaseAction {

	private static Random random = new Random();

	public void show() {
		Map<String, Object> dataModel = new HashMap<String, Object>();
		render("/admin/fileupload.html", dataModel);
	}

	/**
	 * 文件上传
	 */
	@RequestMapping("/file/upload.op")
	@ResponseBody
	public void upload(@RequestParam("uploadfile") MultipartFile file) {
		String fileName = file.getOriginalFilename();
		ResponseData responseData = null;
		String userId = "";
		try {
			userId = String.valueOf(getLoginUserId());
		} catch (Exception e1) {
			responseData = ResponseUtils.fail("请先登录！");
			outResult(responseData);
		}

		InputStream in = null;
		OutputStream out = null;
		File detfile = null;
		try {
			String attachPath = FileResProp.uploadDir + "fileupload"
					+ File.separator + userId;
			String savePath = attachPath;
			File rootPath = new File(savePath);
			if (!rootPath.exists()) {
				rootPath.mkdirs();
			}
			int typeInd = fileName.lastIndexOf(".");
			if (typeInd > 0) {
				fileName = System.currentTimeMillis()
						+ fileName.substring(typeInd);
			}
			String randomStr = String.valueOf(Math.abs(random.nextLong()));
			fileName = randomStr + fileName;
			fileName = fileName.replace("&", "");
			detfile = new File(savePath + File.separator + fileName);
			byte[] bytes = file.getBytes();
			BufferedOutputStream stream = new BufferedOutputStream(
					new FileOutputStream(detfile));
			stream.write(bytes);
			stream.close();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			try {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		FileInfo resultFile = new FileInfo();
		resultFile.setFilePath(detfile.getAbsolutePath());
		resultFile.setFileName(fileName);
		resultFile.setFileSize(detfile.length());
		responseData = ResponseUtils.success("保存成功！");
		responseData.setResult(resultFile);
		outResult(responseData);
	}

	/**
	 * 返回組裝的JSON信息到页面
	 * 
	 * @param responseData
	 */
	public void outResult(ResponseData responseData) {
		if (responseData == null)
			throw new IllegalArgumentException(
					"responseData should not be null");
		try {
			String json = gson.toJson(responseData);
			logger.debug(json);
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().write(json);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 显示上传公用页面
	 */
	public void showUploadPage() {
		try {
			render("/admin/file/uploadfile.html", null);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

}
